package com.ruoyi.web.controller.util;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: oy
 * @description: 请求工具
 * @author: KY
 * @create: 2022-12-17-13:19
 */
public class RequestUtil {

    private static String loginName = "zdzn";
    private static String password = "123456";
    private static String identityId;
    private static String token;

    public static AjaxResult getToken(String url, Object params){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        String jsonString = JSON.toJSONString(params);

        StringEntity entity = new StringEntity(jsonString, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            String result = EntityUtils.toString(responseEntity);
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + result);
            return JSON.parseObject(result, AjaxResult.class);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("请求外部接口 " + url + " 失败！");
    }

    public static void getIdentityIdAndToken(){
        System.out.println("开始获取令牌");
        String url = "https://api.ly-gps.com/lygps-api/v2/auth/getToken";
        Map<String,Object> params = new HashMap<>();
        params.put("loginName",RequestUtil.getLoginName());
        params.put("password",RequestUtil.getPassword());
        AjaxResult result = RequestUtil.getToken(url,params);
        assert result != null;
        System.out.println("========response======="+result);
        if (result.get("code").toString().equals("200")) {
            String data = result.get("data").toString();
            String[] datas = data.substring(1, data.length() - 1).split(",");
            String id = datas[0].split(":")[1].replace("\"", "");
            String tok = datas[1].split(":")[1].replace("\"", "");
            RequestUtil.setIdentityId(id);
            RequestUtil.setToken(tok);
        }
        System.out.println("令牌已获取");
    }

    public static AjaxResult post(String url, Object params){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        String jsonString = JSON.toJSONString(params);

        StringEntity entity = new StringEntity(jsonString, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        httpPost.setHeader("identityId",RequestUtil.getIdentityId());

        httpPost.setHeader("token",RequestUtil.getToken());
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            //响应内容
            String result = EntityUtils.toString(responseEntity);
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + result);
            return JSON.parseObject(result, AjaxResult.class);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("请求外部接口 " + url + " 失败！");
    }

    public static AjaxResult getLocations(List<String> deviceNoList){
        String url = "https://api.ly-gps.com/lygps-api/v2/locate/getDeviceLocate";
        Map<String,Object> params = new HashMap<>();
        params.put("deviceNoList",deviceNoList);
        return RequestUtil.post(url,params);
    }

    public static String getIdentityId() {
        return identityId;
    }

    public static void setIdentityId(String identityId) {
        RequestUtil.identityId = identityId;
    }

    public static String getToken() {
        return token;
    }

    public static void setToken(String token) {
        RequestUtil.token = token;
    }

    public static String getLoginName() {
        return loginName;
    }

    public static void setLoginName(String loginName) {
        RequestUtil.loginName = loginName;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        RequestUtil.password = password;
    }

    @Override
    public String toString() {
        return "RequestUtil{" +
                "identityId='" + identityId + '\'' +
                ", token='" + token + '\'' +
                '}';
    }
}
